#!/usr/bin/env bash
# ******************************************************
# Filename     : backfile.sh
# Last modified: 2018-02-08 17:00


ftpdir=`awk '/IPADDR/' /etc/sysconfig/network-scripts/ifcfg-eth0 |awk -F "=" '{print $2}'`

ftpip="180.169.238.122:10024"
ftpuser="ruoshuiftp"
ftppasswd="dxxx"


# 检测ftp服务器目录
check_dir(){
cat >/tmp/ftpcmd.txt<<EOF
open $ftpip
user "${ftpuser}" "${ftppasswd}"
ls ${ftpdir}
bye
EOF
     lftp -f /tmp/ftpcmd.txt
     echo "" > /tmp/ftpcmd.txt
}

# 创建 ftp服务器目录
ftp_mkdir() {
cat >/tmp/ftpcmd.txt<<EOF
open $ftpip
user "${ftpuser}" "${ftppasswd}"
mkdir -p $ftpdir 
bye
EOF
     lftp -f /tmp/ftpcmd.txt
     echo "" > /tmp/ftpcmd.txt
}

# 创建 ftp服务器目录
ftp_mkdir() {
cat >/tmp/ftpcmd.txt<<EOF
open $ftpip
user "${ftpuser}" "${ftppasswd}"
mkdir -p $ftpdir 
bye
EOF
     lftp -f /tmp/ftpcmd.txt
     echo "" > /tmp/ftpcmd.txt
}

# ftp上传
ftp_upload() {
         ### 上传文件的目录
     uploadpath[1]="/data/backup"

     for p in ${uploadpath[@]}
     do
             ### 过滤要上传的文件 
         uploadfile="`find $p -mmin -600 |grep -E ".gz|.zip"`"
         for f in $uploadfile
         do
cat >/tmp/ftpcmd.txt<<EOF
open $ftpip
user "${ftpuser}" "${ftppasswd}"
cd $ftpdir
mput $f
bye
EOF
         lftp -f /tmp/ftpcmd.txt
         done
     done
echo ""  > /tmp/ftpcmd.txt
}


type lftp 1>/dev/null 2>/dev/null || yum -y install lftp
echo "" > /tmp/ftp_check_dir.txt
check_dir > /tmp/ftp_check_dir.txt 2>&1
word="`cat /tmp/ftp_check_dir.txt|grep "Directory or file not found"`"
if [ -z "${word}" ]
  then
      ftp_upload
  else
      ftp_mkdir
      ftp_upload
      echo "" > /tmp/ftp_check_dir.txt
fi